package com.chenwb.concurrency.future;

import org.junit.Test;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

public class FutureTaskTest {

    private static int i = 0;

    private static ReentrantLock lock = new ReentrantLock();

    private Callable callable = new Callable() {
        @Override
        public Object call() throws Exception {
            lock.lock();
            i++;
            lock.unlock();
            System.out.println("开始执行callable" + (i));
            System.out.println("被执行次数:" + (i));
            Thread.sleep(2000);
            System.out.println("结束执行callable" + (i));
            return 1;
        }
    };

    ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 40, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(300), new ThreadPoolExecutor.CallerRunsPolicy());

    @Test
    public void test() {
        FutureTask futureTask = null;
        for (int i = 0; i < 10; i++) {
            futureTask = new FutureTask(callable);
            executor.execute(futureTask);
        }
        try {
            System.out.println(System.currentTimeMillis());
            System.out.println(futureTask.get());
            System.out.println(System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
